package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/*
添加购物车
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private SpuFeign spuFeign;
    //数据存储到redis中   配置文件要配置redis的地址端口等信息
    @Autowired
    private RedisTemplate redisTemplate;


    //加入购物车
    @Override
    public void add(Integer num, Long id , String username) {

        if (num<=0){
            //当num 小于等于  0  的时候， 要在购物车删除对应的商品
            redisTemplate.boundHashOps("Cart_"+username).delete(id);

            //当购物车为空的时候，直接删除数据域（购物车）
            Long size = redisTemplate.boundHashOps("Cart_" + username).size();
            if (size<=0 || size ==null){
                redisTemplate.delete("Cart_"+username);
            }
            return;
        }
    //查询商品详情信息
        // 1,查询sku
        Result<Sku> sukResult = skuFeign.findById(id);
        Sku sku = sukResult.getData();
        //2，查询spu
        Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());
        Spu spu = spuResult.getData();
        //将购物车信息封装到OrderItem
        OrderItem orderShop = createOrderItem(num, id, sku, spu);
        //将购物车数据存入到Redis:name->namespace->username
        redisTemplate.boundHashOps("Cart_"+username).put(id,orderShop);
    }

    /*
    展示购物车
     */
    @Override
    public List<OrderItem> list(String username) {
        //取出redis对应名字域中的全部符合的数据
        return redisTemplate.boundHashOps("Cart_"+username).values();
    }

    /***
     * 创建order对象
     * @param num
     * @param id
     * @param sku
     * @param spu
     * @return
     */
    private OrderItem createOrderItem(Integer num, Long id, Sku sku, Spu spu) {
        OrderItem order = new OrderItem();
        order.setCategoryId1(spu.getCategory1Id());
        order.setCategoryId2(spu.getCategory2Id());
        order.setCategoryId3(spu.getCategory3Id());
        order.setSpuId(spu.getId());
        order.setSkuId(id);
        order.setName(sku.getName());
        order.setPrice(sku.getPrice());
        order.setNum(num);
        order.setMoney(num *order.getPrice());
        order.setImage(spu.getImage());
        return order;
    }
}
